import React, { FC, Suspense } from 'react'
import * as Type from './type/index'
import { BrowserRouter, HashRouter, Route, Routes, Navigate } from 'react-router-dom'
import Loading from './components/loading'


type Props = {
  routes: Type.RouterList;
  mode?: 'history' | 'hash';
}
let RenderRouter: FC<Props> = ({ routes }) => {
  const homeRouter = (routes: Type.RouterList) => {
    return routes.map((item: Type.RouterItem, index: number) => {
      return < Route key={index} path={item.path} element={item.element ? <item.element /> : <Navigate to={item.to as string} />} >
        {item.children && homeRouter(item.children)}
      </Route >

    })
  }
  return (
    <Suspense fallback={<Loading></Loading>}>
      <Routes>{homeRouter(routes)}</Routes>
    </Suspense>
  );
}

const App: FC<Props> = ({ routes, mode }) =>
  mode === 'history' ? (
    <BrowserRouter>
      <RenderRouter routes={routes} />
    </BrowserRouter>
  ) : (
    <HashRouter>
      <RenderRouter routes={routes} />
    </HashRouter>
  );


export default App
